package org.windblog.core;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.List;
import org.windblog.core.entity.Option;
import org.windblog.core.filter.PersistenceFilter;

public class OptionService {
	private static PersistenceManager pm = null;
			

	private OptionService() {
	}

	/**
	 * ���option �������ȡoption��ֵ
	 * 
	 * @param name
	 *            option�����
	 * @return null ����������Ϊname��option
	 */
	public static String getOptionValue(String name) {
		Option option = getOption(name);
		if (option != null) {
			String value = option.getValue().trim();
			return value;
		} else {
			return null;
		}

	}

	public static void deleteOption(String name)
	{
		Option option = getOption(name);
		if(option != null)
		{
			pm = PersistenceFilter.getManager();
			pm.deletePersistent(option);
		}
	}
	
	/**
	 * ���option �������ȡoption��ʵ��
	 * 
	 * @param name
	 *            option�����
	 * @return null ����������Ϊname��option
	 */
	public static Option getOption(String name) {

		Option target = null;
		Query query = null;
		pm = PersistenceFilter.getManager();
		try {
			query = pm.newQuery(Option.class);
			query.setFilter("name == lastNameParam");
			query.declareParameters("String lastNameParam");
			@SuppressWarnings("unchecked")
			List<Option> optionlist = (List<Option>) query.execute(name);
			if (optionlist.size() == 0) { // ���������option
				return null;
			} else {
				target = optionlist.get(0);
				return target;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally {
			if(query!=null)
				query.closeAll();
		}
	}

	
	public static List<Option> getAllOptions()
	{
		Query query = null;
		pm = PersistenceFilter.getManager();
		try {
			query = pm.newQuery(Option.class);
			@SuppressWarnings("unchecked")
			List<Option> optionlist = (List<Option>) query.execute();
			return optionlist;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally {
			if(query!=null)
				query.closeAll();
		}
	}
	
	/**
	 * ���һ��option�Ƿ����
	 * 
	 * @param name
	 *            option�����
	 * @return true ������
	 */
	public static boolean exist(String name) {
		if (getOption(name) != null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * �޸Ļ򴴽�һ��option
	 * 
	 * @param name
	 * @param value
	 */
	public static void setOption(String name, String value) {
		Option target = null;
		pm = PersistenceFilter.getManager();
		target = getOption(name);
		if (target!=null) {
			target.setValue(value);
			pm.makePersistent(target);
		} else {
			target = new Option();
			target.setName(name);
			target.setValue(value);
			pm.makePersistent(target);
		}
	}

	public static void close() {
		if (pm != null) {
			pm.flush();
			pm.close();
		}
	}

}
